/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    TextInput,
    TouchableOpacity,
    Platform,
    NativeModules,
    ScrollView,
    Alert,
} from 'react-native';
import { NavigationActions } from 'react-navigation';
import StorageUser from '../lib/plugins/StorageUser';
import NavigationBar from '../components/NavigationBar';
import ImageWrapper from '../components/ImageWrapper';
import zhuce from './zhuce';
import loginService from '../lib/services/loginService';
import userService from '../lib/services/userService';
import shopService from '../lib/services/shopService';
import weiService from '../lib/services/weiService';
import *as wechat from 'react-native-wechat';
import * as QQAPI from 'react-native-qq';
import LoadingModal from '../components/LoadingModal';
const {height, width} = Dimensions.get('window');
export default class denglu extends Component {
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
          userName:'',
          passWord:'',
          load:false,
        };
    }
    componentDidMount(){
        wechat.registerApp('wx4d124edcaaba27a0');
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.phone){
                    $this.setState({
                        userName:data.phone
                    })
                }
                
            }).catch(err=> {
                console.log(err)
            });
    }
    render() {
        return (
            <ScrollView>
                <View style={styles.container}>
                    <NavigationBar 
                         titleText="登录"
                         leftStyle={{tintColor:"#fff",marginLeft:15}}
                         rightStyle={{tintColor:"#fff",marginRight:15}}/>
                    <LoadingModal visible={this.state.load} onRequestClose={()=>{console.log('666')}}/>
                    <View style={styles.denglu}>
                        <View style={[styles.shouji,{borderBottomWidth:1,borderBottomColor:"#eee"}]}>
                            <Image style={styles.img1} source={require('../img/icon/phone.png')}/>
                            <TextInput 
                                onChangeText={(text)=>this.aa(text)}  
                                style={{width:200,marginLeft:10,}} 
                                selectionColor={'rgb(79,145,237)'} 
                                underlineColorAndroid="transparent" 
                                placeholder="请输入手机号"
                                defaultValue={this.state.userName}/>
                        </View>
                        <View style={styles.shouji}>
                            <Image style={styles.img1} source={require('../img/icon/password.png')}/>
                                <TextInput 
                                    onChangeText={(text)=>this.cc(text)}  
                                    style={{width:200,marginLeft:10,}} 
                                    selectionColor={'rgb(79,145,237)'}  
                                    underlineColorAndroid="transparent" 
                                    placeholder="输入密码"
                                    secureTextEntry={true}/>
                        </View>
                    </View>
                    <View style={styles.wangji}>
                        <TouchableOpacity onPress={()=>this.gozhuce('忘记密码','zhuce')}><Text style={{marginRight:20,color:"#0894ED"}}>忘记密码?</Text></TouchableOpacity> 
                    </View>
                    <View style={styles.yue}>
                        <TouchableOpacity onPress={()=>this.goIndex()}><View style={{justifyContent:'center',alignItems:'center',height:30,borderWidth:1,borderColor:"#eee",borderRadius:10, backgroundColor:"rgb(79,145,237)",width:(width-30)/2}}><Text style={{color:"#fff"}}>登录</Text></View></TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.gozhuce('注册','zhuce')}><View style={{justifyContent:'center',alignItems:'center',height:30,borderWidth:1,borderColor:"#eee",borderRadius:10,  backgroundColor:"#fff",width:(width-30)/2}}><Text style={{color:"#0894ed"}}>注册</Text></View></TouchableOpacity>
                    </View>
                    <View style={styles.lineBox}>
                        <View style={styles.line}></View>
                        <Text style={{marginLeft:10,marginRight:10,fontSize:12}}>第三方登录</Text>
                        <View style={styles.line}></View>
                    </View>
                    <View style={{flexDirection:'row',marginTop:30}}>
                        <View style={{flex:1,justifyContent:'center',alignItems:'flex-end',height:50,paddingRight:40}}>
                            <TouchableOpacity onPress={()=>this.wxlogin()}>
                                <ImageWrapper style={{width:40,height:40}} icon={'wx'}/>
                            </TouchableOpacity>
                        </View>
                        <View style={{flex:1,justifyContent:'center',alignItems:'flex-start',height:50,paddingLeft:40}}>
                            <TouchableOpacity onPress={()=>this.qqlogin()}>
                                <ImageWrapper style={{width:40,height:40}} icon={'qq'}/>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <TouchableOpacity onPress={()=>this.qq()}>
                        <Text>666</Text>
                    </TouchableOpacity>
                </View>
            </ScrollView>
        );
    }
    qqlogin(){
        var $this = this;
        QQAPI.isQQInstalled()
            .then((res)=>{
                if(res){
                    QQAPI.login('get_simple_userinfo')
                        .then(res=>{
                            // alert(JSON.stringify(res))
                            console.log(res);
                            $this.setState({
                                load:true
                            })
                            weiService.shopTencent(async function(data){
                                console.log(data)
                                alert(JSON.stringify(data))
                                if(data.code==10000){
                                    var object = {};
                                    object.userId = data.data.id;
                                    object.token = data.data['access-token'];
                                    // object.phone = phone;
                                    object.typeId = data.data.type_id;
                                    var routeName = '';
                                    if(object.type_id==1){
                                        if(data.data.status==2){
                                            routeName = 'homePage';
                                        }else{
                                            routeName = 'SubmitInfo';
                                            object.status = data.data.status || 0;
                                            object.submitShopId = data.data.shop_id || 0;
                                        }
                                        
                                    }else{
                                        routeName = 'homePage';
                                    }
                                    await StorageUser._saveUser(object);
                                    $this.setState({
                                        load:false
                                    })
                                    const resetAction = NavigationActions.reset({
                                        index: 0,
                                        actions: [
                                            NavigationActions.navigate({ routeName: routeName})
                                        ]
                                    })
                                    $this.props.navigation.dispatch(resetAction)
                                }
                            },res.openid,'1234567890'/*cid*/,res.access_token)
                        })
                }
            })
            .catch(err => {
                Alert.alert('提示信息', '您还没有安装QQ软件！', [
                    {text: '确定'}
                ]);
            })
        
    }
    getAccessToken(code){
        var $this = this;
        console.log(code)
        var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4d124edcaaba27a0&secret=caf77e505dbaae441a6018972a647d59&code='+code+'&grant_type=authorization_code';
        $this.setState({
            load:true
        })
        fetch(url)
            .then((response)=>{
                // console.log(response)
                return response.text();
            })
            .then((result)=>{ 
                // alert(data)
                var obj = JSON.parse(result);
                console.log(obj)
                weiService.shopIndex(async function(data){
                    console.log(data)
                    if(data.code==10000){
                        var object = {};
                        object.userId = data.data.id;
                        object.token = data.data['access-token'];
                        // object.phone = phone;
                        object.typeId = data.data.type_id;
                        var routeName = '';
                        if(object.type_id==1){
                            if(data.data.status==2){
                                routeName = 'homePage';
                            }else{
                                routeName = 'SubmitInfo';
                                object.status = data.data.status || 0;
                                object.submitShopId = data.data.shop_id || 0;
                            }
                            
                        }else{
                            routeName = 'homePage';
                        }
                        await StorageUser._saveUser(object);
                        $this.setState({
                            load:false
                        })

                        const resetAction = NavigationActions.reset({
                            index: 0,
                            actions: [
                                NavigationActions.navigate({ routeName: routeName})
                            ]
                        })
                        $this.props.navigation.dispatch(resetAction)
                    }
                },obj.openid,''/*cid*/,obj.access_token)
            })
            .catch((error)=>{
                console.log('Request Faild', error);
            })
    }
    wxlogin(){
        var $this = this;
        let scope = 'snsapi_userinfo';
        let state = 'wechat_sdk_demo';
          //判断微信是否安装
        wechat.isWXAppInstalled()
            .then((isInstalled) => {
                // alert(isInstalled)
              if (isInstalled) {
                //发送授权请求
                wechat.sendAuthRequest("snsapi_userinfo")
                  .then(responseCode => {
                //返回code码，通过code获取access_token
                    $this.getAccessToken(responseCode.code);
                  })
                  .catch(err => {
                    Alert.alert('登录授权发生错误：', err.message, [
                      {text: '确定'}
                    ]);
                  })
              } else {
                Platform.OS == 'ios' ?
                  Alert.alert('没有安装微信', '是否安装微信？', [
                    {text: '取消'},
                    // {text: '确定', onPress: () => this.installWechat()}
                  ]) :
                  Alert.alert('没有安装微信', '请先安装微信客户端在进行登录', [
                    {text: '确定'}
                  ])
              }
            })

    }

    qq(){
        NativeModules.CommonModule.getRongToken('bsL5QY_ASaRSaPpTHWDxDDuZSyAf9mbx','142','昵称666','user_598ad68c76d69.jpg')
        // NativeModules.CommonModule.openActivity("ConversationListActivity")
    }

    aa(z){
        this.setState({
            userName:z
        })
    }
    bb(){
        var re = /^1[3578][0-9]{9}$/;
        if(re.test(this.state.userName)){
            alert('你输入的是正确的');
        }else{
            alert('请输入的是正确手机号')
        }

    }
    gozhuce(text,page){
        const {navigate } = this.props.navigation;
        navigate(page,{title:text})
    }
    goIndex(){
        var $this = this;
        var re = /^1[3578][0-9]{9}$/;
        if(!re.test(this.state.userName)){
            alert('手机号格式不正确！');
            return;
        }
        if(this.state.passWord==''){
            alert('密码不能为空！');
            return;
        }
        loginService.login(function(data){
            // alert(JSON.stringify(data))
            $this.setState({
                load:true
            })
            if (data.code==10000) {
                $this.getUserDetails(data.data,$this.state.userName);
            }else{
                // alert('用户名或密码错误！');
                $this.setState({
                    load:false
                })
            }
        },$this.state.userName,$this.state.passWord,'123456789',1)
    }

    getUserDetails(object,phone){
        var $this = this;
        userService.userDetail(async function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                var obj = {};
                obj.userId = data.data.id;
                obj.token = object['access-token'];
                obj.phone = phone;
                obj.typeId = object.type_id;
                // await StorageUser._saveUser(obj);
                // if(object.type_id==1){
                var routeName = '';
                if(object.type_id==1){
                    if(object.status==2){
                        routeName = 'homePage';
                    }else{
                        routeName = 'SubmitInfo';
                        obj.status = object.status || 0;
                        obj.submitShopId = object.shop_id || 0;
                    }
                }else{
                    routeName = 'homePage';
                }
                await StorageUser._saveUser(obj);
                $this.setState({
                    load:false
                })
                const resetAction = NavigationActions.reset({
                    index: 0,
                    actions: [
                        NavigationActions.navigate({ routeName: routeName})
                    ]
                })
                $this.props.navigation.dispatch(resetAction)
            }
        },object['access-token']);
    }

    cc(x){
        this.setState({
            passWord:x
        })
    }
}


const styles = StyleSheet.create({
    container:{
      ...Platform.select({
          ios: {
              marginTop: 20
          },
          android: {
              marginTop:0
          },

      }),
    },
    denglu:{
        backgroundColor:"#fff",
        marginTop:12,
        marginLeft:12,
        marginRight:12,
        borderRadius:10,
    },
    shouji:{
        marginLeft:10,
        marginRight:10,
        flexDirection:"row",
    },
    img1:{
        width:24,
        height:24,
        marginTop:12,
    },
    yue:{
        flexDirection:"row",
        justifyContent:"space-between",
        alignItems:"center",
        marginLeft:10,
        marginRight:10,
    }, 
    wangji:{
        flexDirection:"row-reverse",
        marginTop:12,
        marginBottom:40,
    },
    lineBox:{
        flexDirection:'row',
        alignItems:'center',
        marginTop:50,
        paddingLeft:10,
        paddingRight:10
    },
    line:{
        flex:1,
        borderTopWidth:1,
        borderTopColor:'#ccc'
    }
});

